package com.atguigu.yygh.user.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.atguigu.yygh.user.prop.WeiXinProperties;
import com.atguigu.yygh.user.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: WeiXinController
 * Package: com.atguigu.yygh.user.controller
 * Description:
 *
 * @Author: cqk
 * @Create: 2023/9/25 - 13:15
 * @Version: v1.0
 */
@Controller
@RequestMapping("/user/userinfo/wx")
public class WeiXinController {
    @Autowired
    private WeiXinProperties weiXinProperties;

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/param")
    @ResponseBody
    public R getWinXinLoginParam() throws UnsupportedEncodingException {
        String url = URLEncoder.encode(weiXinProperties.getRedirecturl(), "UTF-8");
        Map<String,Object> map = new HashMap<>();
        map.put("appid",weiXinProperties.getAppid());
        map.put("scope","snsapi_login");
        map.put("redirecturl",url);
        map.put("state",System.currentTimeMillis());

        return R.ok().data(map);
    }

    @GetMapping("/callback")
    public String callback(String state,String code) throws Exception {

        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder append = stringBuilder.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                        .append("?appid=%s")
                                .append("&secret=%s")
                                        .append("&code=%s")
                                                .append("&grant_type=authorization_code");

        String format = String.format(append.toString(),weiXinProperties.getAppid(),weiXinProperties.getAppsecret(),code);

        String result = HttpClientUtils.get(format);
        System.out.println("result = " + result);

        JSONObject jsonObject = JSONObject.parseObject(result);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        System.out.println(access_token);
        System.out.println(openid);

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        UserInfo userInfo =  userInfoService.getOne(queryWrapper);
        if(userInfo==null){
            //说明是首次登录，把用户信息保存在数据库中
            userInfo = new UserInfo();
            userInfo.setOpenid(openid);
            //继续发请求，获取当前用户信息
            StringBuilder sb = new StringBuilder();
            StringBuilder append1 = sb.append("https://api.weixin.qq.com/sns/userinfo?")
                    .append("access_token=%s")
                    .append("&openid=%s");

            String format1 = String.format(append1.toString(),access_token,openid);
            String s = HttpClientUtils.get(format1);

            JSONObject jsonObject1 = JSONObject.parseObject(s);
            String nickname = jsonObject1.getString("nickname");
            userInfo.setNickName(nickname);
            userInfo.setStatus(1);
            //将用户添加到数据库
            userInfoService.save(userInfo);
        }
        if(userInfo.getStatus()==0){
            throw new YyghException(20001,"用户已经被锁定！！！");
        }

        //6.返回用户信息
        Map<String, String> map = new HashMap<>();
        //检查手机号是否为空，为空则是首次登录，需要强制绑定手机号
        if(StringUtils.isEmpty(userInfo.getPhone())){
            map.put("openid",openid);//用于前端是否验证强制绑定手机号
        }else{//说明不是首次登录
            map.put("openid","");
        }


        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);


        String token = JwtHelper.createToken(userInfo.getId(), name);

        map.put("token",token);

        //跳转到前端页面
        return "redirect:http://localhost:3000/weixin/callback?token="+map.get("token")+ "&openid="+map.get("openid")+"&name="+URLEncoder.encode(map.get("name"),"utf-8");
    }
}
